#include <iostream>
#include <winsock2.h>
#include <iphlpapi.h>
#include <icmpapi.h>
#pragma comment(lib, "iphlpapi.lib")
#pragma comment(lib, "ws2_32.lib")

void ping(const char* host) {
    HANDLE hIcmp = IcmpCreateFile();
    if (hIcmp == INVALID_HANDLE_VALUE) {
        std::cout << "创建ICMP句柄失败" << std::endl;
        return;
    }

    DWORD addr = inet_addr(host);
    if (addr == INADDR_NONE) {
        hostent* hp = gethostbyname(host);
        if (!hp) {
            std::cout << "解析主机失败" << std::endl;
            return;
        }
        addr = *(DWORD*)hp->h_addr_list[0];
    }

    char sendData[32] = "abcdefghijklmnopqrstuvwxyz";
    char recvBuf[1024];
    DWORD timeout = 2000;

    for (int i = 0; i < 4; i++) {
        DWORD bytes = IcmpSendEcho(hIcmp, addr, sendData, 32, 
            NULL, recvBuf, 1024, timeout);
        if (bytes > 0) {
            PICMP_ECHO_REPLY pEcho = (PICMP_ECHO_REPLY)recvBuf;
            std::cout << "来自 " << inet_ntoa(*(in_addr*)&pEcho->Address) 
                << " 的回复: 字节=" << pEcho->DataSize 
                << " 时间=" << pEcho->RoundTripTime << "ms" << std::endl;
        } else {
            std::cout << "请求超时" << std::endl;
        }
    }
    IcmpCloseHandle(hIcmp);
}

int main() {
    WSADATA wsaData;
    WSAStartup(MAKEWORD(2, 2), &wsaData);
    ping("127.0.0.1"); // 测试本地
    WSACleanup();
    return 0;
}